package hg.framework.common.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class BaseController {

    /**
     * 获取session对象
     * @return
     */
    protected HttpSession getSession(HttpServletRequest request){
        return request.getSession();
    }

    /**
     * 获取IP
     * @return
     */
    protected String getIp(HttpServletRequest request){
        return request.getRemoteAddr();
    }

    /**
     * 获取头部信息
     * @return
     */
    protected Map<String, String> getHeader(HttpServletRequest request){
        Enumeration<String> headerNameList = request.getHeaderNames();
        headerNameList = (null == headerNameList ? new Enumeration<String>() {
            @Override
            public boolean hasMoreElements() {
                return false;
            }
            @Override
            public String nextElement() {
                return null;
            }
        } : headerNameList);
        Map<String, String> headerMap = new HashMap<>();
        String itemHeaderKey = null;
        String itemHeaderVal = null;
        while(headerNameList.hasMoreElements()) {
            itemHeaderKey = headerNameList.nextElement();
            itemHeaderVal = request.getHeader(itemHeaderKey);
            headerMap.put(itemHeaderKey, itemHeaderVal);
        }
        return headerMap;
    }

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    protected Map<String, Object> getParam(HttpServletRequest request) {
        Map<String, Object> paramMap = new HashMap<>();
        Enumeration<String> paramNameEnum = request.getParameterNames();
        if (null == paramNameEnum) {
            return paramMap;
        }
        String itemParamName = null;
        Object itemParamVal = null;
        while (paramNameEnum.hasMoreElements()) {
            itemParamName = paramNameEnum.nextElement();
            itemParamVal = request.getParameter(itemParamName);
            paramMap.put(itemParamName, itemParamVal);
        }
        return paramMap;
    }
}
